﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Security.Cryptography;
using System.Net;
using System.IO;

namespace Project.Tool
{
    public class Get
    {
		/// <summary>
		/// 实例AppSettingsReader对象
		/// </summary>
		public static AppSettingsReader appReader = new AppSettingsReader();

        #region Url Parameters Type
        /// <summary>
        /// 获取完整请求路径 不带参数
        /// </summary>
        /// <returns></returns>
        public static string RequestUrlAll()
        {
            return RequestTool.GetRequestUrlAllNoParas();
        }

        /// <summary>
        /// 获取请求路径部分Url
        /// </summary>
        /// <returns></returns>
        public static string RequestUrlPath()
        {
            return RequestTool.GetRequestUrlNoParas();
        }

        /// <summary>
        /// 获取请求URL
        /// </summary>
        /// <returns></returns>
        public static string RequestUrl() {
            return RequestTool.GetRequestDomain();
        }

        public static string UrlStr(string Info, string Def = "")
        {
            return RequestTool.RequestString(Info, Def).Replace("%20", " ");
        }
        public static T UrlStr<T>(string Info, string Def = "")
        {
            return RequestTool.RequestString(Info, Def).Replace("%20", " ").ToEF<T>();
        }
        public static string UrlString(string Info, string Def = "")
        {
            return RequestTool.RequestString(Info, Def).Replace("%20", " ");
        }
        public static int UrlInt(string Info, int Def = 0)
        {
            return RequestTool.RequestInt(Info, Def);
        }
        public static decimal UrlDecimal(string Info, decimal Def = 0)
        {
            return RequestTool.RequestDecimal(Info, Def);
        }
        public static double UrlDouble(string Info, double Def = 0)
        {
            return RequestTool.RequestDouble(Info, Def);
        }
        public static DateTime UrlTime(string Info)
        {
            return RequestTool.RequestTime(Info, DateTime.Now);
        }
        public static bool UrlBool(string Info)
        {
            return RequestTool.RequestBool(Info);
        }

        /// <summary>
		/// Url?后面的参数
		/// </summary>
		/// <returns></returns>
		public static int Url()
        {
            try
            {
                return HttpContext.Current.Request.Url.Query.Replace("?", "").Split('#')[0].Split('=')[0].Split('&')[0].ToInt();
            }
            catch
            {
                return 0;
            }

        }
        #endregion

        #region Http Request

        /// <summary>
        /// Http Get 请求
        /// </summary>
        /// <param name="url">网络地址</param>
        /// <param name="parameters">参数[a=1&b=2]</param>
        /// <returns></returns>
        public static string HttpGet(string url,string parameters)
        {
            return HttpGet($"{url}?{parameters}");
        }

        /// <summary>
        /// Http Get 请求
        /// </summary>
        /// <param name="url">网络地址</param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                wbRequest.Method = "GET";
                wbRequest.ContentType = "application/x-www-form-urlencoded";
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sReader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        return sReader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
        }

        /// <summary>
        /// Http Post 请求
        /// </summary>
        /// <param name="url">网络地址</param>
        /// <param name="paramData">携带参数</param>
        /// <param name="headerDic">自定义添加请求头 [Request.Headers.Get(key)]</param>
        /// <returns></returns>
        public static string HttpPost(string url, string paramData = "", Dictionary<string, string> headerDic = null)
        {
            string result = string.Empty;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "POST";
                wbRequest.ContentType = "application/x-www-form-urlencoded";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);

                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }

                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }

                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();

                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        return sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region 地球半径
        private const double EARTH_RADIUS = 6378.137;//地球半径
		private static double rad(double d)
		{
			return d * Math.PI / 180.0;
		}

		/// <summary>
		/// 获取两点距离
		/// </summary>
		/// <param name="lat1">起点</param>
		/// <param name="lng1"></param>
		/// <param name="lat2">目标</param>
		/// <param name="lng2"></param>
		/// <returns></returns>
		public static double Distance(double lat1, double lng1, double lat2, double lng2)
		{
			double radLat1 = rad(lat1);
			double radLat2 = rad(lat2);
			double a = radLat1 - radLat2;
			double b = rad(lng1) - rad(lng2);
			double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a/2),2) +
			Math.Cos(radLat1)*Math.Cos(radLat2)*Math.Pow(Math.Sin(b/2),2)));
			s = s * EARTH_RADIUS;
			s = Math.Round(s * 10000) / 10000;
			return s * 1000;
		}

		/// <summary>    
		/// 计算坐标点的距离    
		/// </summary>    
		/// <param name="begin">开始的经度纬度</param>    
		/// <param name="end">结束的经度纬度</param>    
		/// <returns>距离(公里)*1000=米</returns>    
		//public static double GetDistance(Poin begin, Poin end)
		//{
		//	double lat = begin.RadLat - end.RadLat;
		//	double lng = begin.RadLng - end.RadLng;

		//	double dis = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(lat / 2), 2) + Math.Cos(begin.RadLat) * Math.Cos(end.RadLat) * Math.Pow(Math.Sin(lng / 2), 2)));
		//	dis = dis * EARTH_RADIUS;
		//	dis = Math.Round(dis * 1e4) / 1e4;

		//	return dis * 1000;//乘以1000就是 米数 计算出来的原本是 公里
		//}
		///// <summary>    
		///// 代表经度, 纬度    
		///// </summary>    
		//public class Poin
		//{
		//	/// <param name="lat">纬度 X</param>    
		//	/// <param name="lng">经度 Y</param>    
		//	public Poin(double lat, double lng)
		//	{
		//		this.lat = lat;
		//		this.lng = lng;
		//	}

		//	//  纬度 X    
		//	private double lat;

		//	// 经度 Y    
		//	private double lng;

		//	/// <summary>    
		//	/// 代表纬度 X轴    
		//	/// </summary>    
		//	public double Lat { set; get; }

		//	/// <summary>    
		//	/// 代表经度 Y轴    
		//	/// </summary>    
		//	public double Lng { get; set; }

		//	public double RadLat { get { return lat * Math.PI / 180; } }

		//	public double RadLng { get { return lng * Math.PI / 180; } }
		//}
		#endregion

		/// <summary>
		/// MD5加密字符
		/// </summary>
		/// <param name="PWD"></param>
		/// <returns></returns>
		public static string MD5(string PWD)
		{
			MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
			PWD = BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(PWD))).Replace("-", "").ToLower();
			return PWD;
		}

        #region Request Config Parameters
        /// <summary>
        /// 获取appSettingsReader配置参数
        /// </summary>
        /// <param name="Key">关键字</param>
        /// <returns></returns>
        public static string AppReader(string Key)
        {
            try
            {
                return appReader.GetValue(Key, typeof(string)).ToString();
            }
            catch (Exception e)
            {
                return "";
                //return e.Message;
            }
        }

        /// <summary>
        /// 获取connectionStrings配置参数
        /// </summary>
        /// <param name="Key">关键字</param>
        /// <returns></returns>
        public static string ConReader(string Key)
        {
            try
            {
                return ConfigurationManager.ConnectionStrings[Key].ToString();
            }
            catch (Exception e)
            {
                try
                {
                    return ConnectionStrings[Key];
                }
                catch (Exception ex)
                {

                    return ex.Message;
                }
            }
        }
        #endregion

        #region Select Dic Key
        /// <summary>
        /// 内容分词
        /// </summary>
        /// <param name="val">分词文本</param>
        /// <returns></returns>
        public static Dictionary<string, int> FenCi(string val)
        {
            return WordSpliter.SortByDuplicateCount(WordSpliter.DoSplit(val));
        }

        /// <summary>
        /// 分词内容生成SQL查询条件 
        /// </summary>
        /// <param name="text">查询内容</param>
        /// <param name="rowName">列名称</param>
        /// <returns></returns>
        public static string FenCiWhere(string text, string rowName)
        {

            StringBuilder CiAll = new StringBuilder();

            CiAll.Append(rowName + " like '%" + text + "%' ");

            var AllCi = new List<string>();

            var fenCiAll = FenCi(text);

            if (fenCiAll.Count > 3)
            {
                foreach (var ci in fenCiAll) AllCi.Add(ci.Key);

                for (int i = 0; i < AllCi.Count; i++) for (int j = i + 1; j < AllCi.Count; j++) CiAll.Append("or " + rowName + " like '%" + AllCi[i] + "%' and " + rowName + " like '%" + AllCi[j] + "%' ");

                return CiAll.ToString();
            }
            else
            {
                foreach (var ci in fenCiAll) AllCi.Add(ci.Key);

                for (int i = 0; i < AllCi.Count; i++) CiAll.Append("or " + rowName + " like '%" + AllCi[i] + "%'");

                return CiAll.ToString();
            }

        }
        #endregion

        #region Config Exs

        /// <summary>
        /// 短信验证码
        /// </summary>
        public static int SmsCode { get { return new Random().Next(10000, 999999); } }

        /// <summary>
        /// 加密签名
        /// </summary>
        public static string signName { get { return Get.AppReader("signName"); } }

        /// <summary>
        /// 程序签名
        /// </summary>
        public static string sign { get { return Get.AppReader("Sign"); } }


        #endregion

        #region User Info

        /// <summary>
        /// 连接关键字
        /// </summary>
        public static int urlKey { get { return UrlInt("key"); } }

        /// <summary>
        /// 用户关键字
        /// </summary>
        public static string urlUserKey { get { return UrlStr("userKey"); } }

        /// <summary>
        /// 用户名称
        /// </summary>
        public static string urlUserName { get { return UrlStr("userName"); } }

        /// <summary>
        /// 用户密码
        /// </summary>
        public static string urlUserPass { get { return UrlStr("userPass"); } }

        /// <summary>
        /// 用户密码[MD5]
        /// </summary>
        public static string urlUserPassMD5 { get { return MD5(urlUserPass); } }

        /// <summary>
        /// 账户Token
        /// </summary>
        public static string urlUserToken { get { return MD5(UrlStr("token")); } }

        /// <summary>
        /// 项目ProjectToken
        /// </summary>
        public static string urlProjectToken { get { return MD5(UrlStr("projectToken")); } }

        /// <summary>
        /// 分页[页码]
        /// </summary>
        public static int urlIndex { get { return UrlInt("index", 1); } }

        /// <summary>
        /// 分页[页值]
        /// </summary>
        public static int urlSize { get { return UrlInt("size", 10); } }

        #endregion

        #region ConnectionStrings

#if DEBUG
        /// <summary>
        /// 数据库字典
        /// </summary>
        public static Dictionary<string, string> ConnectionStrings = new Dictionary<string, string>()
                {
                    { "Project", "Data Source=47.104.181.71,1398;database=Project;uid=sa;pwd=zhuJIAN320;" },
                    { "ProjectSocket","Data Source=47.104.181.71,1398;database=Project.Socket;uid=sa;pwd=zhuJIAN320;" }
                };
#else
               /// <summary>
                /// 数据库字典
                /// </summary>
                public static Dictionary<string, string> ConnectionStrings = new Dictionary<string, string>()
                {
                    { "Project", "Data Source=Magey\\SQLEXPRESS;database=Project;uid=sa;pwd=zhuJIAN320;" },
                    { "ProjectSocket","Data Source=Magey\\SQLEXPRESS;database=Project.Socket;uid=sa;pwd=zhuJIAN320;" }
                };
#endif


        #endregion

    }
}
